<script type="text/javascript">
   var numlineas = 0;
   var lcd_txt = '-1';
   function mostrar_paquete(paq)
   {
      $("#paquete_"+paq).modal('show');
      
      var iname = '';
      $('#paquete_'+paq+" input[type='radio']").each(function() {
         if( iname != $(this).attr('name') )
         {
            iname = $(this).attr('name');
            $(this).attr('checked', 'checked');
         }
      });
   }
   function update_lcd(saldo)
   {
      if(saldo != lcd_txt)
      {
         $.ajax({
            type: 'POST',
            url: '{$fsc->url()}',
            dataType: 'html',
            data: 'saldo='+saldo
         });
         lcd_txt = saldo;
      }
   }
   function recalcular()
   {
      var l_uds = 0;
      var l_pvp = 0;
      var l_iva = 0;
      var neto = 0;
      var total_iva = 0;
      
      for(var i=1; i<=numlineas; i++)
      {
         if($("#linea_"+i).length > 0)
         {
            l_uds = parseFloat( $("#cantidad_"+i).val() );
            l_pvp = parseFloat( $("#pvp_"+i).val() );
            l_iva = parseFloat( $("#iva_"+i).val() );
            $("#pvpt_"+i).val( l_uds*l_pvp*(100+l_iva)/100 );
            
            neto += l_uds*l_pvp;
            total_iva += l_uds*l_pvp*l_iva/100;
         }
      }
      neto = fs_round(neto, {#FS_NF0#});
      total_iva = fs_round(total_iva, {#FS_NF0#});
      $("#tpv_total").html( show_precio(neto+total_iva) );
      $("#tpv_total2").val( fs_round(neto+total_iva, {#FS_NF0#}) );
      update_lcd(neto + total_iva);
   }
   function linea_sum_ud(num,value)
   {
      var paqid = $("#paquete_"+num).val();
      var udl = parseInt( $("#cantidad_"+num).val() );
      udl += value;
      if(udl < 1)
      {
         if(paqid != '')
         {
            for(var i=1; i<=numlineas; i++)
            {
               if( $("#paquete_"+i).val() == paqid )
                  $("#linea_"+i).remove();
            }
         }
         else
            $("#linea_"+num).remove();
      }
      else
      {
         if(paqid != '')
         {
            for(var i=1; i<=numlineas; i++)
            {
               if( $("#paquete_"+i).val() == paqid )
                  $("#cantidad_"+i).val(udl);
            }
         }
         else
            $("#cantidad_"+num).val(udl);
      }
      recalcular();
   }
   function ajustar_pvpt(num)
   {
      if($("#linea_"+num).length > 0)
      {
         var l_uds = parseFloat( $("#cantidad_"+num).val() );
         var l_pvp = 0;
         var l_iva = parseFloat( $("#iva_"+num).val() );
         var l_pvpt = parseFloat( $("#pvpt_"+num).val() );
         var neto = 0;
         var total_iva = 0;
         
         if( !isNaN(l_pvpt) )
         {
            $("#pvp_"+num).val( 100*l_pvpt/(l_uds*(100+l_iva)) );
            
            for(var i=1; i<=numlineas; i++)
            {
               if($("#linea_"+i).length > 0)
               {
                  l_uds = parseFloat( $("#cantidad_"+i).val() );
                  l_pvp = parseFloat( $("#pvp_"+i).val() );
                  l_iva = parseFloat( $("#iva_"+i).val() );
                  
                  neto += l_uds*l_pvp;
                  total_iva += l_uds*l_pvp*l_iva/100;
               }
            }
            
            neto = fs_round(neto, {#FS_NF0#});
            total_iva = fs_round(total_iva, {#FS_NF0#});
            $("#tpv_total").html( show_precio(neto+total_iva) );
            $("#tpv_total2").val( fs_round(neto+total_iva, {#FS_NF0#}) );
            update_lcd(neto + total_iva);
         }
      }
   }
   function add_articulo(ref,pvp,iva,paquete,descripcion)
   {
      numlineas += 1;
      $("#numlineas").val(numlineas);
      pvp = parseFloat(pvp);
      iva = parseFloat(iva);
      var pvpt_itype = "text";
      if(paquete != '' && pvp == 0)
         pvpt_itype = "hidden";
      $("#tpv_albaran").append("<tr id=\"linea_"+numlineas+"\"><td>"+ref+" "+descripcion+"</td>\n\
         <td align=\"center\">\n\
            <input type=\"hidden\" id=\"paquete_"+numlineas+"\" name=\"paquete_"+numlineas+"\" value=\""+paquete+"\"/>\n\
            <input type=\"hidden\" name=\"referencia_"+numlineas+"\" value=\""+ref+"\"/>\n\
            <input type=\"hidden\" id=\"pvp_"+numlineas+"\" name=\"pvp_"+numlineas+"\" value=\""+pvp+"\"/>\n\
            <input type=\"hidden\" id=\"iva_"+numlineas+"\" name=\"iva_"+numlineas+"\" value=\""+iva+"\"/>\n\
            <input class=\"btn btn-sm btn-warning\" type=\"button\" value=\"-\" onclick=\"linea_sum_ud("+numlineas+",-1)\"/> &nbsp;\n\
            <input type=\"text\" id=\"cantidad_"+numlineas+"\" name=\"cantidad_"+numlineas+
               "\" onkeyup=\"recalcular()\" autocomplete=\"off\" value=\"1\" size=\"1\"/> &nbsp;\n\
            <input class=\"btn btn-sm btn-primary\" type=\"button\" value=\"+\" onclick=\"linea_sum_ud("+numlineas+",1)\"/></td>\n\
         <td align=\"right\">\n\
            <input class=\""form-control\"" type=\""+pvpt_itype+"\" id=\"pvpt_"+numlineas+"\" name=\"pvpt_"+numlineas+"\" value=\""+(pvp*(100+iva)/100)+
               "\" autocomplete=\"off\" size=\"6\" onclick=\"this.select()\" onkeyup=\"ajustar_pvpt('"+numlineas+"')\"/>\n\
         </td>\n\
         </tr>");
      recalcular();
      fs_hide_popups();
   }
   function add_paquete(ref)
   {
      var paqid = Math.random()*11;
      var fpaq = document.getElementById('f_p_'+ref);
      var pvp = fpaq.pvp.value;
      var iva = fpaq.iva.value;
      var descripcion = fpaq.descripcion.value;
      add_articulo(ref,pvp,iva,paqid,descripcion);
      var grupos = fpaq.grupos.value;
      var radiob;
      var ref2;
      for(var i=1; i<=grupos; i++)
      {
         radiob = fpaq.elements["grupo_"+i];
         for(var j=0; j<radiob.length; j++)
         {
            ref2 = radiob[j].value;
            if( radiob[j].checked )
               break;
         }
         add_articulo(ref2,0,0,paqid,'');
      }
   }
   function more_tickets(value)
   {
      var num = parseInt($("#num_tickets").val()) + parseInt(value);
      if(num < 0)
         $("#num_tickets").val(0);
      else
         $("#num_tickets").val(num);
   }
   $(document).ready(function() {
      $("div.popup label").hover(function() {
         $('#' + $(this).attr('for')).attr('checked', 'checked');
      });
      $("#paquetes").click(function() {
         $("#all_paquetes").modal('show');
      });
      {loop="$fsc->familias"}
      $("#fam_{$value->codfamilia}").click(function(event) {
         $("#articulos_{$value->codfamilia}").modal('show');
      });
      {/loop}
      $("#b_guardar_ticket").click(function() {
         $("#fin_ticket").modal('show');
         document.form_tpv_albaran.efectivo.value = '0.00';
         document.form_tpv_albaran.cambio.value = '0.00';
         document.form_tpv_albaran.efectivo.select();
      });
      $("#tpv_efectivo").keyup(function() {
         $("#tpv_cambio").val( number_format(parseFloat($(this).val()) - parseFloat($("#tpv_total2").val()),2,'.','') );
      });
      $("#b_cancelar_ticket").click(function() {
         window.location.href = "{$fsc->url()}&delete="+prompt('Introduce el código del ticket:');
      });
      $("#b_cerrar_caja").click(function() {
         if( confirm("¿Realmente deseas cerrar la caja?") )
            window.location.href = "{$fsc->url()}&cerrar_caja=TRUE";
      });
      $("#b_opciones_tpv").click(function(event) {
         event.preventDefault();
         $("#modal_opciones_tpv").modal('show');
      });
      update_lcd(0);
   });
</script>

<form name="form_tpv_albaran" action="{$fsc->url()}" method="post">
   <input type="hidden" name="petition_id" value="{$fsc->random_string()}"/>
   <input type="hidden" id="numlineas" name="numlineas" value="0"/>
   <div class="table-responsive">
      <table class="table table-hover">
         <tr>
            <td valign="top" width="180px">
               <ul class="tpv_familias">
               {if condition="$fsc->paquetes"}<li id="paquetes">PAQUETES</li>{/if}
               {loop="$fsc->familias"}<li id="fam_{$value->codfamilia}">{$value->descripcion}</li>{/loop}
               </ul>
            </td>
            <td valign="top">
               
               <div class="modal fade" id="modal_opciones_tpv">
                  <div class="modal-dialog">
                     <div class="modal-content">
                        <div class="modal-header">
                           <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                           <h4 class="modal-title">Opciones</h4>
                        </div>
                        <div class="modal-body">
                           <div class="form-group">
                              Fecha:
                              <input class="form-control datepicker" type="text" name="fecha" value="{$fsc->today()}" size="10"/>
                           </div>
                           <div class="form-group">
                              <a href="{$fsc->cliente->url()}">Cliente:</a>
                              <select name="cliente" class="form-control">
                                 {loop="$fsc->cliente->all_full()"}
                                    {if condition="$value->is_default()"}
                                    <option value="{$value->codcliente}" selected="selected">{$value->nombre}</option>
                                    {else}
                                    <option value="{$value->codcliente}">{$value->nombre}</option>
                                    {/if}
                                 {else}
                                    <option value="">¡¡¡No tienes clientes!!!</option>
                                 {/loop}
                              </select>
                           </div>
                           <div class="form-group">
                              <a href="{$fsc->almacen->url()}">Almacén</a>:
                              <select name="almacen" class="form-control">
                                 {loop="$fsc->almacen->all()"}
                                    {if condition="$value->is_default()"}
                                       <option value="{$value->codalmacen}" selected='selected'>{$value->nombre}</option>
                                    {else}
                                       <option value="{$value->codalmacen}">{$value->nombre}</option>
                                    {/if}
                                 {/loop}
                              </select>
                           </div>
                           <div class="form-group">
                              <a href="{$fsc->serie->url()}">Serie</a>:
                                 <select name="serie" class="form-control">
                                    {loop="$fsc->serie->all()"}
                                       {if condition="$value->is_default()"}
                                          <option value="{$value->codserie}" selected='selected'>{$value->descripcion}</option>
                                       {else}
                                          <option value="{$value->codserie}">{$value->descripcion}</option>
                                       {/if}
                                    {/loop}
                                 </select>
                           </div>
                           <div class="form-group">
                              Forma de pago:
                              <select name="forma_pago" class="form-control">
                                 {loop="$fsc->forma_pago->all()"}
                                    {if condition="$value->is_default()"}
                                       <option value="{$value->codpago}" selected="selected">{$value->descripcion}</option>
                                    {else}
                                       <option value="{$value->codpago}">{$value->descripcion}</option>
                                    {/if}
                                 {/loop}
                              </select>
                           </div>
                           <div class="form-group">
                              Divisa:
                              <select name="divisa" class="form-control">
                                 {loop="$fsc->divisa->all()"}
                                    {if condition="$value->is_default()"}
                                       <option value="{$value->coddivisa}" selected="selected">{$value->descripcion}</option>
                                    {else}
                                       <option value="{$value->coddivisa}">{$value->descripcion}</option>
                                    {/if}
                                 {/loop}
                              </select>
                           </div>
                           <div class="form-group">
                              <div class="bg-advice">Haz un ticket para que se guarden los cambios.</div>
                           </div>
                        </div>
                        <div class="modal-footer">
                           <button class="btn btn-sm btn-primary" type="button" type="submit" onclick="this.disabled=true;this.form.submit();">
                              <span class="glyphicon glyphicon-floppy-disk"></span>
                              &nbsp; Guardar
                           </button>
                        </div>
                     </div>
                  </div>
               </div>
               
               <div class="well well-sm">
                  <div class="row">
                     <div class="col-lg-6 col-md-6 col-sm-6 text-left">
                        Atiende: <a href="{$fsc->agente->url()}">{$fsc->agente->get_fullname()}</a>
                     </div>
                     <div class="col-lg-6 col-md-6 col-sm-6 text-right" id="tpv_total">
                        {$fsc->show_precio(0)}
                     </div>
                  </div>
                  <br />
                  <div class="table-responsive">
                     <table class="table table-hover" id="tpv_albaran">
                        <tr>
                           <th>Artículo</th>
                           <th>Ud.</th>
                           <th class="text-right">Total+IVA</th>
                        </tr>
                     </table>
                  </div>
                  <br/><br/>
                  <div class="text-right">
                     <input class="btn btn-sm btn-primary" type="button" value="Guardar ticket" id="b_guardar_ticket"/>
                     <br/>
                  </div>
               </div>
            </td>
         </tr>
      </table>
   </div>
   
   <div class="modal fade" id="fin_ticket">
      <div class="modal-dialog">
         <div class="modal-content">
            <div class="modal-body">
               <div class="table-responsive">
                  <table class="table table-hover">
                     <tr>
                        <td class="text-right">Total:</td>
                        <td><input class="tpv_total" type="text" name="total2" value="0.00" size="5" id="tpv_total2" disabled="disabled"/> {$fsc->simbolo_divisa()}</td>
                     </tr>
                     <tr>
                        <td class="text-right">Efectivo:</td>
                        <td><input class="tpv_total" type="text" name="efectivo" value="0.00" size="5" id="tpv_efectivo" autocomplete="off"/> {$fsc->simbolo_divisa()}</td>
                     </tr>
                     <tr>
                        <td class="text-right">Cambio:</td>
                        <td><input class="tpv_total" type="text" name="cambio" value="0.00" size="5" id="tpv_cambio" autocomplete="off"/> {$fsc->simbolo_divisa()}</td>
                     </tr>
                     <tr>
                        <td class="text-right">Observaciones:</td>
                        <td><textarea name="observaciones"></textarea></td>
                     </tr>
                     <tr>
                        <td class="text-right">Nº de tickets:</td>
                        <td>
                           <input class="btn btn-sm btn-warning" type="button" value=" - " onclick="more_tickets('-1')"/>
                           <input class="form-control" type="text" id="num_tickets" name="num_tickets" value="2" size="2"/>
                           <input class="btn btn-sm btn-primary" type="button" value=" + " onclick="more_tickets('1')"/>
                        </td>
                     </tr>
                     <tr>
                        <td colspan="2">&nbsp;</td>
                     </tr>
                     <tr>
                        <td><input class="btn btn-sm btn-primary" type="button" value="cancelar" onclick="fs_hide_popups()"/></td>
                        <td class="text-right">
                           <input class="btn btn-sm btn-primary" type="submit" value="finalizar" onclick="this.disabled=true;this.form.submit();"/>
                        </td>
                     </tr>
                  </table>
               </div>
            </div>
         </div>
      </div>
   </div>
</form>

<div class="modal fade" id="all_paquetes">
   <div class="modal-dialog">
      <div class="modal-content">
         <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title">Paquetes</h4>
         </div>
         <div class="modal-body">
            <ul class="items">
            {loop="$fsc->paquetes"}
               <li class="touch" onclick="mostrar_paquete('{$value->referencia}')">
                  {$value->articulo->referencia}
                  {if condition="$value->articulo->imagen_url()"}
                     <br/><img src="{$value->articulo->imagen_url()}" alt="{$value->referencia}"/><br/>
                  {else}
                     <br/><img src="view/img/unknown.png" alt="{$value->referencia}"/><br/>
                  {/if}
                  {$fsc->show_precio($value->articulo->pvp_iva())}
               </li>
            {/loop}
            </ul>
         </div>
      </div>
   </div>
</div>


{loop="$fsc->paquetes"}
<form name="f_p_{$value1->referencia}" id="f_p_{$value1->referencia}" class="form" action="{$fsc->url()}" method="post">
   <input type="hidden" name="proveedor"/>
   <div class="modal fade" id="paquete_{$value1->referencia}">
      <div class="modal-dialog">
         <div class="modal-content">
            <div class="modal-header">
               <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
               <h4 class="modal-title">PAQUETE: {$value1->referencia} &nbsp; &nbsp; {$fsc->show_precio($value1->articulo->pvp_iva())}</h4>
            </div>
            <div class="modal-body">
               <input type="hidden" name="pvp" value="{$value->articulo->pvp}"/>
               <input type="hidden" name="iva" value="{$value->articulo->get_iva()}"/>
               <input type="hidden" name="descripcion" value="{$value->articulo->descripcion}"/>
               <input type="hidden" name="grupos" value="{$value->grupos}"/>
               {loop="$value1->get_grupos()"}
               <div class="grupo grupo_paquete">
                  <h2>Grupo {$value2}:</h2>
                  {loop="$value1->subpaquetes"}
                     {if condition="$value3->grupo==$value2"}
                     <input type="radio" name="grupo_{$value2}" value="{$value3->referencia}" id="g_{$value1->referencia}_{$value3->referencia}" style="display:none;"/>
                     <label for="g_{$value1->referencia}_{$value3->referencia}">{$value3->referencia}</label>
                     {/if}
                  {/loop}
                  <input type="radio" name="grupo_{$value2}" value="" style="display:none;"/>
               </div>
               {/loop}
            </div>
            <div class="modal-footer">
               <input type="button" class="btn btn-sm btn-warning" value="cancelar" onclick="fs_hide_popups()"/>
               <input type="button" class="btn btn-sm btn-primary" value="confirmar" onclick="add_paquete('{$value1->referencia}')"/>
            </div>
         </div>
      </div>
   </div>
</form>
{/loop}

{loop="$fsc->familias"}
   <div class="modal fade" id="articulos_{$value1->codfamilia}">
      <div class="modal-dialog">
         <div class="modal-content">
            <div class="modal-header">
               <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
               <h4 class="modal-title">{$value1->descripcion}</h4>
            </div>
            <div class="modal-body">
               <ul class="items">
               {loop="$fsc->articulos"}
                  {if condition="$value2->codfamilia==$value1->codfamilia"}
                  <li class="touch" onclick="add_articulo('{$value2->referencia}','{$value2->pvp}','{$value2->get_iva()}','','{$value2->descripcion}')">
                     {$value2->referencia}
                     {if condition="$value2->imagen_url()"}
                        <br/><img src="{$value2->imagen_url()}" alt="{$value2->referencia}"/><br/>
                     {else}
                        <br/><img src="view/img/unknown.png" alt="{$value2->referencia}"/><br/>
                     {/if}
                     {$fsc->show_precio($value2->pvp_iva())}
                  </li>
                  {/if}
               {/loop}
               </ul>
            </div>
         </div>
      </div>
   </div>
{/loop}

<div class="hidden">
   <iframe src="http://localhost:10080" height="0"></iframe>
</div>
